package com.lujieni.netty.c3;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class TestNettyPromise {

    public static void main(String[] args) {

        //给我生成一个promise对象
        DefaultPromise<Integer> promise = new DefaultPromise<>(new NioEventLoopGroup().next());

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
                promise.setSuccess(100); // invoke promise's listener
                int i = 10 / 0;
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }).start();

        // add a listener when the promise is done
        promise.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                System.out.println(Thread.currentThread().getName());
                if(future.isSuccess()){
                    System.out.println("Promise succeeded: " + future.getNow());
                }else{
                    System.out.println("Promise failure because: " + future.cause());
                }
            }
        });


    }


}
